package a66weding.com.jiehuntong.activity.me;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yanzhenjie.recyclerview.swipe.Closeable;
import com.yanzhenjie.recyclerview.swipe.OnSwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.hotel.shop.HomeProductdetailActivity;
import a66weding.com.jiehuntong.adapter.MenuAdapter;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.FiltrateClassifyBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeCollectBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.StatusBarUtils;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;

import static a66weding.com.jiehuntong.application.DataWareHourse.mContext;


/**
 * 我的—收藏模块
 * Created by Administrator on 2016/7/7.
 */
public class MeCollectActivity extends MeBaseActivity implements View.OnClickListener, OnNetResultListener {
    private LinearLayout mBackLay;
    private TextView mBackContentTv;
    private TextView mHeaderTitleTv;
    private TextView mRightTitleTv;
    private SwipeRefreshLayout xRefreshView;
    private SwipeMenuRecyclerView recyclerView;
    private ArrayList<MeCollectBean.DataBean> dataList = new ArrayList<MeCollectBean.DataBean>();
    private MeCollectBean mMeCollectBean;
    private LinearLayout mShowList;
    private LinearLayout mNoList;
    private PopupWindow mPopWindow;
    private RelativeLayout mRelaHeah;
    private ArrayList<FiltrateClassifyBean.DataBean> mFiltrateList = new ArrayList<FiltrateClassifyBean.DataBean>();
    private FiltrateClassifyBean filtrateClassifyBean;
    private String category = "";
    private MenuAdapter adapter;
    private int page = 1;
    private boolean isNeedNextRequset=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_collect);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("MeCollectActivityAdapter", this);
        initview();
        initRefreshView();
    }
    /**
     * 页面初始化数据调用的方法
     */
    private void initData() {
        // 请求列表的网络请求
        if (page!=1){
            Tools.showDialog(this);
        }
        String myUrl = UrlDealUtil.getRealUrlNoIdApi(RequestCode.GET_COLLECTIONLIST);
        String url = myUrl + "&pageIndex=" + page + "&memberID=" + UrlDealUtil.getMemberID() + "&CategoryID=" + category;
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url,
                this, MeCollectBean.class, RequestCode.GET_COLLECTIONLIST);
        HttpHandleUtil.executeCommonGet(MeCollectActivity.this, httpRequestBean);
        // 请求筛选分类的请求
        String meUrl = RequestCode.GET_PRODUCTCATEGORYBYPID;
        HttpRequestBean httpRequestBeans = new HttpRequestBean(RequestCode.GETREQUEST,
                meUrl, this, FiltrateClassifyBean.class, RequestCode.GET_PRODUCTCATEGORYBYPID);
        HttpHandleUtil.executeCommonGet(this, httpRequestBeans);
    }
    private void initview() {
        mBackLay = (LinearLayout) findViewById(R.id.lay_head_backlay);
        mBackContentTv = (TextView) findViewById(R.id.headleft_title_tv);
        mHeaderTitleTv = (TextView) findViewById(R.id.headcenter_title_tv);
        mRightTitleTv = (TextView) findViewById(R.id.headright_title_tv);
        mShowList = (LinearLayout) findViewById(R.id.ll_show_list);
        mNoList = (LinearLayout) findViewById(R.id.ll_no_list);
        mRelaHeah = (RelativeLayout) findViewById(R.id.rl_mypublic_heahview);
        mBackContentTv.setText("我的");
        mHeaderTitleTv.setText("我的收藏");
        mRightTitleTv.setText("筛选");
        mBackLay.setOnClickListener(this);
        mRightTitleTv.setOnClickListener(this);
    }
    @TargetApi(Build.VERSION_CODES.M)
    private void initRefreshView() {
        adapter = new MenuAdapter(null);
        xRefreshView = (SwipeRefreshLayout) findViewById(R.id.help_refresh);
        xRefreshView.setColorSchemeResources(R.color.colorMainRed);
        xRefreshView.post(new Runnable() {
            @Override
            public void run() {
                xRefreshView.setRefreshing(true);
                    page = 1;
                    initData();
            }
        });
        recyclerView = (SwipeMenuRecyclerView) findViewById(R.id.lv_me_indent_collect);
        xRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                xRefreshView.setRefreshing(true);
                page = 1;
                initData();
            }
        });
        recyclerView.addOnScrollListener(mOnScrollListener);
        //线性布局
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        recyclerView.setHasFixedSize(true);// 如果Item够简单，高度是确定的，打开FixSize将提高性能。
        // 为SwipeRecyclerView的Item创建菜单就两句话，不错就是这么简单：
        recyclerView.setSwipeMenuCreator(swipeMenuCreator);// 设置菜单创建器。
        recyclerView.setSwipeMenuItemClickListener(menuItemClickListener);   // 设置菜单Item点击监听。
        recyclerView.setLongPressDragEnabled(false);// 关闭拖拽，就这么简单一句话。
        recyclerView.setItemViewSwipeEnabled(false);// 关闭滑动删除。
        adapter.setOnItemClickListener(new MenuAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                int i_id = adapter.getItemData(position).getI_Id();
                Intent intent = new Intent(MeCollectActivity.this, HomeProductdetailActivity.class);
                intent.putExtra("productId",i_id);
                startActivity(intent);
            }
        });
    }
    /**
     * 加载更多
     */
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (!recyclerView.canScrollVertically(1)) {// 手指不能向上滑动了
                if (isNeedNextRequset) {
                    initData();
                }
            }
        }
    };
        /**
         * 菜单创建器。
         */
        private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
                // MATCH_PARENT 自适应高度，保持和内容一样高；也可以指定菜单具体高度，也可以用WRAP_CONTENT。
                int width = getResources().getDimensionPixelSize(R.dimen.bigsize300);
                int height = getResources().getDimensionPixelSize(R.dimen.bigsize315);//ViewGroup.LayoutParams.MATCH_PARENT;
                // 添加右侧的，如果不添加，则右侧不会出现菜单。()
                SwipeMenuItem deleteItem = new SwipeMenuItem(mContext)
                        .setBackgroundDrawable(R.drawable.selector_mainred)
                        // .setImage(R.mipmap.cane)
                        .setText("取消收藏") // 文字，还可以设置文字颜色，大小等。。
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。
            }
        };
        /**
         * 菜单点击监听。
         */
        private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
            @Override
            public void onItemClick(Closeable closeable, final int adapterPosition, int menuPosition, int direction) {
                closeable.smoothCloseMenu();// 关闭被点击的菜单。
                if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                    // 获取商家ID
                    final MeCollectBean.DataBean md= adapter.getItemData(adapterPosition);
                    int businessId =  md.getI_Id();
                    String myUrl = UrlDealUtil.getRealUrlNewIdApi(RequestCode.POST_COLLECTIONCANCEL);
                    String url = myUrl + "&productID=" + businessId;
                    HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                            new OnNetResultListener() {
                                @Override
                                public void onSucess(SuccessBean sucessbean) {
                                    adapter.remove(adapterPosition);
                                }
                                @Override
                                public void onError(ErrorBean errorBean) {
                                }
                            }, CommonResultBean.class, RequestCode.POST_COLLECTIONCANCEL);
                    HttpHandleUtil.executeCommonPost(MeCollectActivity.this, httpRequestBean);
                } else if (direction == SwipeMenuRecyclerView.LEFT_DIRECTION) {
                    Toast.makeText(mContext, "list第" + adapterPosition + "; 左侧菜单第" + menuPosition, Toast.LENGTH_SHORT).show();
                }
            }
        };


        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.lay_head_backlay: //点击我的，返回到上一级界面
                    finish();
                    break;
                case R.id.headright_title_tv: //点击筛选,根据分类进行选择
                    if (mPopWindow != null) {
                        mPopWindow.dismiss();
                        mPopWindow = null;
                    }
                    showPopupWindow();
                    break;
            }
        }

        //显示窗体
        private void    showPopupWindow() {
            //设置contentView
            View contentView = LayoutInflater.from(MeCollectActivity.this).inflate(R.layout.popupwindow_filtrate, null);
            mPopWindow = new PopupWindow(contentView,
                    -1, -2, true);
            mPopWindow.setContentView(contentView);
            mPopWindow.setBackgroundDrawable(new ColorDrawable(
                    Color.TRANSPARENT));
            //设置各个控件的点击响应
            ListView lv_popupwindow = (ListView) contentView.findViewById(R.id.lv_popupwindow);
            lv_popupwindow.setAdapter(new MeAdapter());
            lv_popupwindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    category = "" + mFiltrateList.get(position).getI_Id();
                    page = 1;
                    isNeedNextRequset=true;
                    initData();
                    if (mPopWindow != null) {
                        mPopWindow.dismiss();
                        mPopWindow = null;
                    }
                }
            });

            //显示PopupWindow
            View rootview = LayoutInflater.from(MeCollectActivity.this).inflate(R.layout.activity_main, null);
            mPopWindow.showAtLocation(rootview, Gravity.TOP, 0, mRelaHeah.getHeight() + StatusBarUtils.getStatusHeight(this));
        }

        @Override
        public void onSucess(SuccessBean sucessbean) {
            Object data = sucessbean.getData();
            if (data instanceof MeCollectBean) {
                Tools.dismissWaitDialog();
                mMeCollectBean = (MeCollectBean) data;
                dataList = (ArrayList<MeCollectBean.DataBean>) mMeCollectBean.getData();
                if (dataList.size() == 0 && page == 1) {
                    mNoList.setVisibility(View.VISIBLE);
                    mShowList.setVisibility(View.GONE);
                } else {
                    if (dataList.size() == 0) {
                        CUtils.showToast("您就收藏了这么多哦!");
                        isNeedNextRequset = false;
                    } else {
                        mNoList.setVisibility(View.GONE);
                        mShowList.setVisibility(View.VISIBLE);
                        if (page == 1) {
                            adapter.clear();
                        }
                        page++;
                        xRefreshView.setRefreshing(false);
                        adapter.append(dataList);
                    }
                }
                // 设置菜单创建器。
                recyclerView.setSwipeMenuCreator(swipeMenuCreator);
                // 设置菜单Item点击监听。
                recyclerView.setSwipeMenuItemClickListener(menuItemClickListener);

            } else if (data instanceof CommonResultBean) {
                Toast.makeText(MeCollectActivity.this, "收藏取消成功", Toast.LENGTH_SHORT).show();
            } else if (data instanceof FiltrateClassifyBean) {
                filtrateClassifyBean = (FiltrateClassifyBean) data;
                mFiltrateList = (ArrayList<FiltrateClassifyBean.DataBean>) filtrateClassifyBean.getData();
                // 向集合中再添加一个元素
                FiltrateClassifyBean.DataBean classifyBean = new FiltrateClassifyBean.DataBean();
                classifyBean.setNvc_Name("全部");
                classifyBean.setI_Id(0);
                mFiltrateList.add(0, classifyBean);
            }
        }

        @Override
        public void onError(ErrorBean errorBean) {
            if (xRefreshView!=null){
                xRefreshView.setRefreshing(false);
            }

            Tools.dismissWaitDialog();
            Toast.makeText(MeCollectActivity.this, "请求数据失败", Toast.LENGTH_SHORT).show();
        }
        class MeAdapter extends BaseAdapter {

            @Override
            public int getCount() {
                return mFiltrateList.size();
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view;
                ViewHolder holder;
                if (convertView != null) {
                    view = convertView;
                    holder = (ViewHolder) view.getTag();
                } else {
                    view = View.inflate(getApplicationContext(), R.layout.item_popupwindow_filtrate, null);
                    holder = new ViewHolder();
                    holder.tv_listview_popupwindow = (TextView) view.findViewById(R.id.tv_listview_popupwindow);
                    view.setTag(holder);
                }
                holder.tv_listview_popupwindow.setText(mFiltrateList.get(position).getNvc_Name());
                return view;
            }
        }

    static class ViewHolder {
        TextView tv_listview_popupwindow;
        ImageView imageView2;
    }
}
